package com.wenwan.manage.interceptor;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.wenwan.manage.util.InterceptorUtil;

/**
 * 签名拦截
 * 
 * @author Admin
 *
 */
public class AutographInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		// TODO Auto-generated method stub
		@SuppressWarnings("unchecked")
		Enumeration<String> en = arg0.getParameterNames();
		Map<String, String> map = new TreeMap<String, String>();
		String key = null;
		String value = null;
		// 将参数存入map
		System.out.println("后台获取的参数：");
		while (en.hasMoreElements()) {
			key = en.nextElement();
			System.out.print(key);
			System.out.print(":");
			value = arg0.getParameter(key);
			System.out.println(value);
			if (value != null) {
				map.put(key, value);
			}

		}
		// 移除map里的签名并返回---签名1
		String auth_1 = map.remove("auth");
		System.out.println("前端签名：" + auth_1);
		// -----前端签名
		// map转换成json字符串，并去除所有 " 引号
		String jsonStr = new Gson().toJson(map).replaceAll("[\"]+", "");
		System.out.println("后台排序：" + jsonStr);
		// -----{aaa:test,id:3FD4A673F9CE460CB85F6709BC3991C3,name:sherry}
		String salt = "02AD8F051AD51A3CE653AC57A0C0DB1D";
		// 加盐
		jsonStr += salt;
		System.out.println("加盐后的字符串：" + jsonStr);
		//
		// 并进行双重md5加密，得到---签名2
		String auth_2 = DigestUtils.md5Hex(DigestUtils.md5Hex(jsonStr).toUpperCase()).toUpperCase();
		System.out.println("后台签名：" + auth_2);
		// -----98c8fe50fdfb1f02799bc627b351eff3
		// 校验签名
		if (auth_1 != null && auth_1.equals(auth_2)) {
			// 校验成功
			System.out.println("签名校验成功");
			return true;
		} else {
			System.out.println("");
			Map<String, Object> dto = new HashMap<String, Object>();
			dto.put("data", false);
			dto.put("code", "000000");
			dto.put("msg", "签名校验失败");
			InterceptorUtil.returnJsonMessage(arg1, dto);
			return false;
		}

	}

}
